package com.asktgapp.user.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.asktgapp.R;
import com.asktgapp.application.MyApplication;
import com.asktgapp.user.fragment.LoginFragment;
import com.asktgapp.user.fragment.RegisterFragment;
import com.umeng.socialize.UMShareAPI;

import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * time:2018/1/16
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class LoginActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    private TextView mLoginTv, mRegisterTv;
    private ViewPager mViewPager;
    private PagerAdapter mPagerAdapter;
    private int reload;
    private long firstClickBack = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.getInstance().addActivity(this);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
//        reload = getIntent().getIntExtra("reload", 1);
        mLoginTv = (TextView) findViewById(R.id.tv_login);
        mRegisterTv = (TextView) findViewById(R.id.tv_register);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOffscreenPageLimit(2);
        mLoginTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewPager.setCurrentItem(0);
                mLoginTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.mipmap.ico_sj);
                mRegisterTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            }
        });
        mRegisterTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewPager.setCurrentItem(1);
                mRegisterTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.mipmap.ico_sj);
                mLoginTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            }
        });
        getPermissions();
    }


    private void getPermissions() {
        EasyPermissions.requestPermissions(this,
                "应用程序将要获取以下权限：内存读取权限,本地相册读取及手机状态权限",
                0,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA);
    }

    //    当权限被成功申请的时候执行回调，requestCode是代表你权限请求的识别码，list里面装着申请的权限的名字：
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        switch (requestCode) {
            case 0:
                break;
        }
    }

    //当权限申请失败的时候执行的回调
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
//处理权限名字字符串
        StringBuffer sb = new StringBuffer();
        for (String str : perms) {
            sb.append(str);
            sb.append("\n");
        }
        sb.replace(sb.length() - 2, sb.length(), "");
        boolean isE= false;
        switch (requestCode) {
            case 0:
                isE= true;
                break;
        }
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
//            Toast.makeText(this,"已拒绝权限" + sb + "并不再询问",Toast.LENGTH_SHORT);
            new AppSettingsDialog
                    .Builder(this)
                    .setRationale("您未授予程序相关权限，可能会导致部分功能无法正常使用，是否打开设置进行授权")
                    .setPositiveButton("好")
                    .setNegativeButton("不行")
                    .build()
                    .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    public class PagerAdapter extends FragmentPagerAdapter {

        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            switch (position) {
                case 0://首页
                    return new LoginFragment();
                case 1://点检
                    return new RegisterFragment();
            }
            return new LoginFragment();
        }

        @Override
        public int getCount() {
            return 2;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondClickBack = System.currentTimeMillis();
            if (secondClickBack - firstClickBack > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出应用", Toast.LENGTH_SHORT).show();
                firstClickBack = secondClickBack;
                return true;
            } else {
                MyApplication.getInstance().removeALLActivity();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

}
